// ZENrs FFI接口 - Zig端实现

const std = @import("std");
const allocator = std.heap.page_allocator;

// 从Rust导入的增强函数
extern "C" fn zenrs_create_message(
    message_type: u32,
    sender_id: u64,
    target_id: u64,
    data_size: u64
) [*c]ZenrsMessage;

extern "C" fn zenrs_free_message(message_ptr: [*c]ZenrsMessage) void;

extern "C" fn zenrs_process_string(input: [*c]const u8) [*c]u8;

extern "C" fn zenrs_free_string(str_ptr: [*c]u8) void;

extern "C" fn zenrs_get_version() [*c]const u8;

extern "C" fn zenrs_fibonacci(n: u32) u64;

extern "C" fn zenrs_fibonacci_iterative(n: u32) u64;

extern "C" fn zenrs_create_config() [*c]ZenrsConfig;

extern "C" fn zenrs_free_config(config_ptr: [*c]ZenrsConfig) void;

extern "C" fn zenrs_update_config(
    config_ptr: [*c]ZenrsConfig,
    debug_level: u32,
    log_to_console: bool,
    max_threads: u32
) c_int;

// 新增的增强功能函数
extern "C" fn zenrs_create_complex_data(
    id: u64,
    name: [*c]const u8,
    values_count: u32,
) [*c]ZenrsComplexData;

extern "C" fn zenrs_free_complex_data(data_ptr: [*c]ZenrsComplexData) void;

extern "C" fn zenrs_process_with_callback(
    data: [*c]u8,
    callback: *const fn(context: [*c]u8, result: c_int, data: [*c]u8) callconv(.C) c_int,
    context: [*c]u8
) c_int;

extern "C" fn zenrs_async_operation(
    operation_id: [*c]u64,
    callback: *const fn(result: c_int, user_data: [*c]u8) callconv(.C) void,
    user_data: [*c]u8
) c_int;

extern "C" fn zenrs_cancel_async_operation(operation_id: u64) c_int;

extern "C" fn zenrs_create_shared_memory(size: u64) [*c]ZenrsSharedMemory;

extern "C" fn zenrs_free_shared_memory(memory_ptr: [*c]ZenrsSharedMemory) void;

extern "C" fn zenrs_lock_shared_memory(memory_ptr: [*c]ZenrsSharedMemory, timeout_ms: u64) c_int;

extern "C" fn zenrs_unlock_shared_memory(memory_ptr: [*c]ZenrsSharedMemory) c_int;

extern "C" fn zenrs_batch_process(
    items: [*c][*c]u8,
    item_count: u32,
    process_fn: *const fn(context: [*c]u8, result: c_int, data: [*c]u8) callconv(.C) c_int,
    context: [*c]u8
) c_int;

extern "C" fn zenrs_get_last_error(buffer: [*c]u8, buffer_size: u64) c_int;

extern "C" fn zenrs_convert_data_type(
    src_data: [*c]const u8,
    src_type: u32,
    dst_data: [*c]u8,
    dst_type: u32,
    data_size: u64
) c_int;

// 定义增强的错误码
pub const ZENRS_OK: c_int = 0;
pub const ZENRS_ERROR_INVALID_PARAM: c_int = -1;
pub const ZENRS_ERROR_OUT_OF_MEMORY: c_int = -2;
pub const ZENRS_ERROR_NOT_FOUND: c_int = -3;
pub const ZENRS_ERROR_UNSUPPORTED: c_int = -4;
pub const ZENRS_ERROR_TIMEOUT: c_int = -5;
pub const ZENRS_ERROR_LOCK_FAILED: c_int = -6;
pub const ZENRS_ERROR_CALLBACK_ERROR: c_int = -7;
pub const ZENRS_ERROR_BUFFER_TOO_SMALL: c_int = -8;
pub const ZENRS_ERROR_INTERNAL: c_int = -9;

// 定义共享的数据结构
export const ZenrsMessage = extern struct {
    message_type: u32,
    sender_id: u64,
    target_id: u64,
    data_size: u64,
    data_ptr: [*c]u8,
};

export const ZenrsConfig = extern struct {
    debug_level: u32,
    log_to_console: bool,
    max_threads: u32,
    reserved: [1024]u8,
};

// 增强功能：复杂数据结构
export const ZenrsComplexData = extern struct {
    id: u64,
    name_ptr: [*c]const u8,
    values_count: u32,
    values_ptr: [*c]u64,
    config_ptr: [*c]ZenrsConfig,
    is_valid: bool,
};

// 增强功能：共享内存描述符
export const ZenrsSharedMemory = extern struct {
    buffer: [*c]u8,
    size: u64,
    is_locked: bool,
    owner_id: u64,
    creation_time: u64,
};

// 导出函数供Rust调用

/// 获取系统信息
export fn zenrs_zig_get_system_info(buffer: [*c]u8, buffer_size: u64) c_int {
    if (buffer == null or buffer_size < 1) {
        return ZENRS_ERROR_INVALID_PARAM;
    }
    
    // 系统信息字符串
    const system_info = "ZENrs Exokernel (Zig Layer)\n" ++
                      "Architecture: x86_64\n" ++
                      "Memory: 16GB\n" ++
                      "CPUs: 8 cores\n" ++
                      "Version: 1.0.0";
    
    // 检查缓冲区大小是否足够
    const info_len = system_info.len;
    if (buffer_size < info_len + 1) { // +1 for null terminator
        return ZENRS_ERROR_INVALID_PARAM;
    }
    
    // 复制系统信息到缓冲区
    @memcpy(buffer[0..info_len], system_info);
    buffer[info_len] = 0; // 添加null终止符
    
    return @as(c_int, info_len);
}

/// 创建一个简单的Zig对象
export fn zenrs_zig_create_object(size: u64) [*c]u8 {
    const object = allocator.alloc(u8, @intCast(usize, size)) catch {
        return null;
    };
    
    // 初始化对象（例如填充一些模式）
    @memset(object, 0xAA);
    
    return @ptrCast([*c]u8, object.ptr);
}

/// 释放Zig对象
export fn zenrs_zig_free_object(object_ptr: [*c]u8, size: u64) void {
    if (object_ptr != null) {
        const object = @ptrCast([*]u8, object_ptr)[0..@intCast(usize, size)];
        allocator.free(object);
    }
}

/// ZIG端的字符串处理函数
export fn zenrs_zig_process_string(input: [*c]const u8) [*c]u8 {
    // 将C字符串转换为Zig字符串
    const input_str = std.mem.sliceTo(input, 0);
    
    // 处理字符串
    const processed = std.fmt.allocPrint(
        allocator, 
        "Processed by Zig: {s}", 
        .{input_str}
    ) catch return null;
    
    return @ptrCast([*c]u8, processed.ptr);
}

/// 释放Zig字符串
export fn zenrs_zig_free_string(str_ptr: [*c]u8) void {
    if (str_ptr != null) {
        const str = std.mem.sliceTo(str_ptr, 0);
        allocator.free(str);
    }
}

/// 获取当前时间戳
export fn zenrs_zig_get_timestamp() u64 {
    return std.time.milliTimestamp();
}

/// 增强功能：Zig端的回调函数处理
export fn zenrs_zig_process_with_callback(
    data: [*c]u8,
    callback: *const fn(context: [*c]u8, result: c_int, data: [*c]u8) callconv(.C) c_int,
    context: [*c]u8
) c_int {
    if (callback == null) {
        return ZENRS_ERROR_INVALID_PARAM;
    }
    
    // 调用回调函数
    return callback(context, ZENRS_OK, data);
}

/// 增强功能：Zig端的异步操作
export fn zenrs_zig_async_operation(
    operation_id: [*c]u64,
    task_data: [*c]u8,
    data_size: u64
) c_int {
    if (operation_id == null || data_size == 0) {
        return ZENRS_ERROR_INVALID_PARAM;
    }
    
    // 为了简化，这里只是模拟异步操作
    // 实际应用中应该使用Zig的async/await功能
    *operation_id = std.time.milliTimestamp();
    
    // 在实际应用中，这里应该启动一个真正的异步任务
    std.debug.print("Started async operation {} in Zig\n", .{*operation_id});
    
    return ZENRS_OK;
}

/// 增强功能：Zig端的共享内存创建
export fn zenrs_zig_create_shared_memory(size: u64) [*c]ZenrsSharedMemory {
    if (size == 0) {
        return null;
    }
    
    // 分配共享内存缓冲区
    const buffer = allocator.alloc(u8, @intCast(usize, size)) catch {
        return null;
    };
    
    // 创建共享内存描述符
    const shared_memory = allocator.create(ZenrsSharedMemory) catch {
        allocator.free(buffer);
        return null;
    };
    
    shared_memory.* = ZenrsSharedMemory{
        .buffer = buffer.ptr,
        .size = size,
        .is_locked = false,
        .owner_id = 0, // 临时值
        .creation_time = std.time.milliTimestamp(),
    };
    
    return shared_memory;
}

/// 增强功能：Zig端的共享内存释放
export fn zenrs_zig_free_shared_memory(memory_ptr: [*c]ZenrsSharedMemory) void {
    if (memory_ptr != null) {
        const memory = memory_ptr.*;
        
        if (memory.buffer != null && memory.size > 0) {
            const buffer = memory.buffer[0..@intCast(usize, memory.size)];
            allocator.free(buffer);
        }
        
        allocator.destroy(memory_ptr);
    }
}

/// 增强功能：Zig端的共享内存锁定
export fn zenrs_zig_lock_shared_memory(memory_ptr: [*c]ZenrsSharedMemory, timeout_ms: u64) c_int {
    if (memory_ptr == null) {
        return ZENRS_ERROR_INVALID_PARAM;
    }
    
    if (memory_ptr.*.is_locked) {
        // 简单的超时机制
        if (timeout_ms > 0) {
            // 在实际应用中，应该使用条件变量或其他同步原语
            const start_time = std.time.milliTimestamp();
            while (memory_ptr.*.is_locked) {
                if (std.time.milliTimestamp() - start_time > timeout_ms) {
                    return ZENRS_ERROR_TIMEOUT;
                }
                // 短暂休眠避免CPU占用过高
                std.time.sleep(1 * std.time.ns_per_ms);
            }
        } else {
            return ZENRS_ERROR_LOCK_FAILED;
        }
    }
    
    memory_ptr.*.is_locked = true;
    return ZENRS_OK;
}

/// 增强功能：Zig端的共享内存解锁
export fn zenrs_zig_unlock_shared_memory(memory_ptr: [*c]ZenrsSharedMemory) c_int {
    if (memory_ptr == null) {
        return ZENRS_ERROR_INVALID_PARAM;
    }
    
    memory_ptr.*.is_locked = false;
    return ZENRS_OK;
}

/// 增强功能：Zig端的批量数据处理
export fn zenrs_zig_batch_process(
    items: [*c][*c]u8,
    item_count: u32,
    process_fn: *const fn(context: [*c]u8, item: [*c]u8) callconv(.C) c_int,
    context: [*c]u8
) c_int {
    if (items == null || process_fn == null || item_count == 0) {
        return ZENRS_ERROR_INVALID_PARAM;
    }
    
    var success_count: u32 = 0;
    
    var i: u32 = 0;
    while (i < item_count) : (i += 1) {
        const item = items[i];
        const result = process_fn(context, item);
        
        if (result == ZENRS_OK) {
            success_count += 1;
        }
    }
    
    return @as(c_int, success_count);
}

/// 增强功能：Zig端的复杂数据结构创建
export fn zenrs_zig_create_complex_data(
    id: u64,
    name: [*c]const u8,
    values_count: u32,
) [*c]ZenrsComplexData {
    if (name == null || values_count == 0) {
        return null;
    }
    
    // 分配复杂数据结构
    const complex_data = allocator.create(ZenrsComplexData) catch {
        return null;
    };
    
    // 分配值数组
    const values = allocator.alloc(u64, @intCast(usize, values_count)) catch {
        allocator.destroy(complex_data);
        return null;
    };
    
    // 初始化值数组
    for (values) |*val, i| {
        val.* = @intCast(u64, i); // 简单初始化
    }
    
    // 创建配置对象
    const config = zenrs_create_config();
    if (config == null) {
        allocator.free(values);
        allocator.destroy(complex_data);
        return null;
    }
    
    // 设置复杂数据结构字段
    complex_data.* = ZenrsComplexData{
        .id = id,
        .name_ptr = name, // 注意：不复制name，使用传入的指针
        .values_count = values_count,
        .values_ptr = values.ptr,
        .config_ptr = config,
        .is_valid = true,
    };
    
    return complex_data;
}

/// 增强功能：Zig端的复杂数据结构释放
export fn zenrs_zig_free_complex_data(data_ptr: [*c]ZenrsComplexData) void {
    if (data_ptr != null) {
        const data = data_ptr.*;
        
        // 释放值数组
        if (data.values_ptr != null && data.values_count > 0) {
            const values = data.values_ptr[0..@intCast(usize, data.values_count)];
            allocator.free(values);
        }
        
        // 释放配置对象
        if (data.config_ptr != null) {
            zenrs_free_config(data.config_ptr);
        }
        
        allocator.destroy(data_ptr);
    }
}

/// 增强功能：Zig端的错误信息获取
export fn zenrs_zig_get_last_error(buffer: [*c]u8, buffer_size: u64) c_int {
    // 在实际应用中，应该返回真实的错误信息
    const error_msg = "No recent error in Zig";
    
    if (buffer == null || buffer_size == 0) {
        return ZENRS_ERROR_INVALID_PARAM;
    }
    
    const msg_len = error_msg.len;
    const copy_len = if (msg_len < buffer_size) msg_len else buffer_size - 1;
    
    @memcpy(buffer[0..copy_len], error_msg[0..copy_len]);
    if (copy_len < buffer_size) {
        buffer[copy_len] = 0; // 添加null终止符
    }
    
    return @as(c_int, copy_len);
}

/// 增强功能：Zig端的类型转换
export fn zenrs_zig_convert_data_type(
    src_data: [*c]const u8,
    src_type: u32,
    dst_data: [*c]u8,
    dst_type: u32,
    data_size: u64
) c_int {
    if (src_data == null || dst_data == null || data_size == 0) {
        return ZENRS_ERROR_INVALID_PARAM;
    }
    
    // 这里只是简单复制内存
    // 实际应用中应该实现真实的类型转换逻辑
    @memcpy(dst_data[0..@intCast(usize, data_size)], src_data[0..@intCast(usize, data_size)]);
    
    return ZENRS_OK;
}

/// 测试Rust和Zig的FFI互操作
pub fn test_ffi_interop() !void {
    std.debug.print("\n=== Testing FFI Interoperability ===\n", .{});
    
    // 1. 测试版本信息
    const version = zenrs_get_version();
    std.debug.print("Version: {s}\n", .{std.mem.sliceTo(version, 0)});
    
    // 2. 测试字符串处理
    const input_str = "Hello from Zig!";
    const processed_str = zenrs_process_string(input_str.ptr);
    defer zenrs_free_string(processed_str);
    
    std.debug.print("Original string: {s}\n", .{input_str});
    std.debug.print("Processed by Rust: {s}\n", .{std.mem.sliceTo(processed_str, 0)});
    
    // 3. 测试斐波那契函数
    const fib_n = 40;
    const start_time = std.time.nanoTimestamp();
    const fib_result = zenrs_fibonacci(fib_n);
    const end_time = std.time.nanoTimestamp();
    const duration = (end_time - start_time) / 1_000_000;
    
    std.debug.print("Fibonacci({}) = {} (took {}ms)\n", .{fib_n, fib_result, duration});
    
    // 测试迭代版本
    const iter_start_time = std.time.nanoTimestamp();
    const iter_fib_result = zenrs_fibonacci_iterative(fib_n);
    const iter_end_time = std.time.nanoTimestamp();
    const iter_duration = (iter_end_time - iter_start_time) / 1_000_000;
    
    std.debug.print("Iterative Fibonacci({}) = {} (took {}ms)\n", .{fib_n, iter_fib_result, iter_duration});
    
    // 4. 测试配置对象
    const config = zenrs_create_config();
    defer zenrs_free_config(config);
    
    std.debug.print("Default config: debug_level={}, log_to_console={}, max_threads={}\n",
        .{config.*.debug_level, config.*.log_to_console, config.*.max_threads});
    
    // 更新配置
    const update_result = zenrs_update_config(config, 2, false, 8);
    if (update_result == ZENRS_OK) {
        std.debug.print("Updated config: debug_level={}, log_to_console={}, max_threads={}\n",
            .{config.*.debug_level, config.*.log_to_console, config.*.max_threads});
    } else {
        std.debug.print("Failed to update config, error code: {}\n", .{update_result});
    }
    
    // 5. 测试消息创建和释放
    const msg_data_size = 128;
    const message = zenrs_create_message(1, 100, 200, msg_data_size);
    defer zenrs_free_message(message);
    
    if (message != null) {
        std.debug.print("Created message: type={}, sender={}, target={}, data_size={}\n",
            .{message.*.message_type, message.*.sender_id, message.*.target_id, message.*.data_size});
        
        // 填充消息数据
        if (message.*.data_ptr != null) {
            const data = message.*.data_ptr[0..@intCast(usize, msg_data_size)];
            @memset(data, 0xBB);
            std.debug.print("Message data buffer initialized\n", .{});
        }
    } else {
        std.debug.print("Failed to create message\n", .{});
    }
    
    std.debug.print("=== FFI Interoperability Tests Complete ===\n\n", .{});
}

// 主函数（用于测试）
pub fn main() !void {
    try test_ffi_interop();
}

// 注意：在实际的项目中，这个文件需要被适当地集成到Zig的构建系统中
// 特别是需要链接到Rust生成的库文件